<!--
 * @Author: Hzt
 * @Date: 2024-01-11 17:48:43
 * @LastEditTime: 2024-05-17 20:07:21
 * @LastEditors: Hzt
 * @Description: 
 * @FilePath: \cty_admin\src\components\page-modal\src\page-modal.vue
-->
<template>
  <div class="page-modal">
    <el-dialog :width="width" :class="customClass" v-bind="$attrs" destroy-on-close v-on="$listeners">
      <slot slot="header" />
      <BaseForm ref="baseForm" :form-data="formData" v-bind="modalFormConfig" @updateFormData="updateFormData" />
      <slot />
      <template slot="footer">
        <span class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" :loading="btnLoading" @click="handleConfirmClick">
            确 定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import BaseForm from "@/base-ui/form";
export default {
  components: {
    BaseForm,
  },
  props: {
    width: {
      type: String,
      default: '600px'
    },
    customClass: String,  // 添加class属性
    btnLoading: {
      type: Boolean,
      default: false,
    },
    modalFormConfig: {
      type: Object,
      required: true,
    },
    modalFormData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      formData: {},
    };
  },
  watch: {
    modalFormData: {
      handler(newValue) {
        for (const item of this.modalFormConfig.formItems) {
          this.$set(this.formData, item.field, newValue[item.field]);
        }
      },
    },
    immediate: true,
  },
  methods: {
    cancel() {
      this.$emit("update:visible", false);
    },
    handleConfirmClick() {
      this.$refs.baseForm.formValidate((valid) => {
        if (valid) {
          this.$emit("confirm", this.formData);
        }
      });
    },
    updateFormData({ value, field }) {
      if (field in this.formData) {
        this.formData[field] = value;
        return;
      }
      this.$set(this.formData, field, value);
    },
  },
};
</script>

<style lang="scss" scoped></style>
